# -*- coding : utf-8 -*-
import threading
import requests
import base64
import hashlib
import datetime
import cv2
import json
from PIL import Image
from common.utils import *
from concurrent.futures import ThreadPoolExecutor
from mes_updata import MesServers
# 首先将图片读入
# 由于要发送json，所以需要对byte进行str解码


def get_save_pa():
    D = get_max_disk()
    s = f'{D}:/data/save'
    mkdir(s)
    return s


def get_task_pa():
    aa = get_save_pa()
    s = f'{aa}/tasks'
    mkdir(s)
    return s


def get_url():
    url = config['pic_server_url']
    print('pic_server_url', url)
    pa = get_save_pa()
    urlfn = f'{pa}/url.json'
    if os.path.exists(urlfn):
        data = json.load(open(urlfn, 'r'))
        if 'url' in data.keys():
            url = data['url']

    return url


def put_img_client(imgfns, prod, datenow, key, end ,ss):
    try:
        data = {}
        img_fns = []
        # url = get_url()
        url = "http://10.175.145.21:5000/v1/mdzx_detect"
        for i, img_fn in enumerate(imgfns):
            if os.path.exists(img_fn):
                bb = open(img_fn, 'rb').read()
                base64img = base64.b64encode(bb).decode('ascii')
                data["IMAGES"] = base64img
        data['SN'] = prod  # 条码
        # data['class'] = '结构检测'
        data['ITEMS_CATEGORY_ID'] = key
        data['TIME'] = datenow
        if end:
            data['end'] = 'NG'
        else:
            data['end'] = 'OK'
        cc = json.dumps(data)
        print('put_img_client post', url)
        headers = {
            'Content-Type': 'application/json'
        }
        response = requests.request("POST", url, headers=headers, data=cc, timeout=50)
        datas = json.loads(response.text)
        logger.info(datas)
        # codee = datas["code"]
        # pht_url = datas["res"]
        # logger.info(datas)
        # if config['post_prod']:
        #     url2 = config['prod_url']
        #     requests.post(url2, data=prod)
        #     iteid = ss.isid
        #     steid = ss.ssid
        # dats = json.dumps({
        #         "ORG_ID": "123",
        #         "SN": prod,
        #         "RESULT_LIST": [{
        #                         "ITEMS_CATEGORY_ID": iteid,
        #                         "STANDARDS_ITEM_ID": steid,
        #                         "CHECKED_RESULT": data['end'],
        #                         "URL":pht_url
        #         }],
        #         "AI_TYPE": "SUPPLIER",
        #         "LINE_CODE": ""
        #     })
        # currentTime, rando, kee, betime, entime = text()
        # headers = {
        #     'currentTime': currentTime,
        #     'random': rando,
        #     'url': 'https://qmsuatapi.midea.com/api',
        #     'key': kee,
        #     'Content-Type': 'application/json'
        # }
        # body = requests.post(url, data=dats,headers=headers, timeout=5)
        # body = json.loads(body.text)
        # logger.info(body)
        # print('fuwuqi')
        # pass
        return 1
    except Exception as e:
        errdata =f"upload_data_err:{e}"
        print('put_img_client', e)
        logger.error(errdata)
        return 0


class BoundThreadPoolExecutor(ThreadPoolExecutor):
    # 对ThreadPoolExecutor 进行重写，给队列设置边界
    def __init__(self, qsize: int = None, *args, **kwargs):
        super(BoundThreadPoolExecutor, self).__init__(*args, **kwargs)
        self._work_queue = queue.Queue(qsize)


def select_imgfns(imgfns, end):
    outng = []
    outok = []
    for x in imgfns:
        if '.jpg' not in x.lower():
            continue
        if '_ret' in x.lower():
            continue
        if '_NG_' in x:
            outng.append(x)
        else:
            outok.append(x)
    out = outng + outok
    # t = 5 if end else 1
    # if 'max_update_pic' in config:
    #     t = config['max_update_pic']
    #     out = out[-t:]
    return out


def upload_task(ss, taskfn):
    try:
        #if not config['upimgs']:
        #    return 0
        try:
            data = json.load(open(taskfn, 'r'))
        except Exception as e:
            print(f'upload_task failed')
            pass
        # print('upload_task', taskfn)
        # os.remove(f'{taskfn}')
        if 'data' in data.keys():
            try:
                imgfns, prod, datenow, key, end = data['data']
            except Exception as e:
                imgfns, prod, key, end = data['data']
                datenow = datetime.datetime.now().strftime('%Y%m%d')
            imgfns = select_imgfns(imgfns, end)
            t0 = time.time()
            logger.info('data get success')
            ret = put_img_client(imgfns, prod, datenow, key, end,ss)
            t1 = time.time()
            tt = t1 - t0
            if ret:
                print(f'upimgs task ok {taskfn} {len(imgfns)} imgs {tt:.2f}s')
                os.remove(taskfn)
            else:
                print(f'upimgs task fail {taskfn} {len(imgfns)} imgs {tt:.2f}s')
    # except BlockingIOError as e:
    except Exception as e:
        # os.remove(taskfn)
        print('upload_task:', e)
        os.remove(taskfn)
        pass

    return 1

def upload_work_thd(ss):
    print("上传线程进入工作状态")
    # 告知PLC CAM处于READY状态可以接受数据
    max_workers = 5
    pool = ThreadPoolExecutor(max_workers=max_workers)
    while ss.running:
        # print(f'cam_ready {i}')
        try:
            pa = get_task_pa()
            li = [f'{pa}/{x}' for x in os.listdir(pa) if '.json' in x]
            if ss.use_thread:
                rets = []
                for taskfn in li:
                    if ss.running:
                        all_task = [pool.submit(upload_task, taskfn) for taskfn in li]
                        rets.append(all_task)
                [ret.result() for ret in rets]
            else:
                for taskfn in li:
                    if ss.running:
                        upload_task(ss, taskfn)
        except Exception as e:
            # i = random.randint(0, 1000) % 2
            logger.info(f'upload_work_thd err {str(e)}')
            continue

        # time.sleep(0.1)
    print("上传线程进结束")
    return 0


def text():
  import random
  ur = 'https://qmsuatapi.midea.com/api'
  now = datetime.datetime.now()
  pre_now = now - datetime.timedelta(hours=1)
  currentTime = now.strftime('%Y-%m-%d')
  betime = pre_now.strftime('%Y-%m-%d %H:%M:%S')
  entime = now.strftime('%Y-%m-%d %H:%M:%S')
  rando = random.randint(1000000, 9999999)
  rando = str(rando)
  kee = currentTime+ur+rando
  kee = ''.join(map(str, kee))
  input_name = hashlib.md5()
  input_name.update(kee.encode("utf-8"))
  kee = (input_name.hexdigest()).lower()
  return currentTime,rando,kee,betime,entime


def class_id_get(ss):
    while True:
        try:
            currentTime, rando, kee, betime, entime = text()
            url = "https://qmsuatapi.midea.com/api/SnAiFile/GetAiStandardsItem"

            payload = json.dumps({
                "ORG_ID": "123",
                "DATETIME_BEGIN": betime,
                "DATETIME_END": entime,
                "LINE_CODE": ""
            })
            headers = {
                'currentTime': currentTime,
                'random':rando,
                'url':'https://qmsuatapi.midea.com/api',
                'key':kee,
                'Content-Type': 'application/json'
            }
            # log.info(datass)
            try:
                response = requests.request("POST", url, headers=headers, data=payload, timeout=3)
                data = json.loads(response.text)
                sid = data['Data']['ITEM_CATEGORY_ID']
                iid = data['Data']['STANDARDS_ITEM_ID']
                ss.ssid = sid
                ss.isid = iid
                logger.info(data)
            except Exception as e:
                datass = f"message_update{e}"
                logger.error(datass)
                # log.error(datass)
        except Exception as e:
            datass = f"message_update_err{e}"
            logger.error(datass)
        time.sleep(3600)
        # print(data)
    return 0

class UploadImages:
    def __init__(self, ss=None, saoma=None) -> None:
        self.thread_work = None
        self.running = False
        self.use_thread = 1
        self.qq = queue.Queue()
        self.ssid = None
        self.isid = None
        self.ssw = None
        # self.oss = OssTH()
        self.mes = MesServers()
        # self.ssw = ScadaServer(ss)
        self.ss = ss
        # if saoma is not None:
        #    saoma.callback = get_saoma_callback(self.ssw)
        self.start()

    def __del__(self):
        self.stop()

    def put(self, imgfns, saoma, key, end):
        imgfn = []
        prod = saoma.product
        t0 = time.time()
        tt = t0 - saoma.product_time
        isstopline1 = 0
        # if tt > config['stopline_time']:
        #     isstopline1 = 1
        if len(imgfns) == 0:
            print('没有图片')
            return 0
        for i in range(len(imgfns)):
            if imgfns[i].find('ret') != -1:
                pass
            else:
                imgfn.append(imgfns[i])
        pa = get_task_pa()
        s = get_time_stamp()
        task_fn = f'{pa}/upimg_task_{s}.json'
        processtime = 0.1 + random.random() * 0.1
        # updata_scada(self.ssw, config, prod, end, isstopline1)
        self.mes.hefei_message_update(prod, end)
        processtime = f'{processtime}'
        # scantime = get_time13()
        # datatime = get_datetime_str()
        datenow = datetime.datetime.now().strftime('%Y%m%d')
        # scanresult = get_datetime_str()
        # 'OK/NG/NULLIFY/SCANFAIL'
        scanresult = 'NG' if end else 'OK'
        scantype = 1
        # ossdata = [prod, processtime, scantime, datatime, scanresult, scantype]
        # data = {'data': [imgfn, prod, datenow, key, end], 'up_ok': 0, 'ossdata': ossdata}
        data = {'data': [imgfn, prod, datenow, key, end], 'up_ok': 0}
        json.dump(data, open(task_fn, 'w'))
        # self.qq.put([imgfns, prod, key, end])
        return 0

    def start(self):
        if self.thread_work is None:
            self.running = True

            self.thread_work = threading.Thread(
                target=upload_work_thd, args=(self,))
            # self.thread_work = threading.Thread(
            #     target=class_id_get, args=(self,))
            self.thread_work.start()
            return 1

        return 0

    def stop(self):
        # if self.oss is not None:
        #     self.oss.stop()
        if self.ssw is not None:
            self.ssw.stop()
        if self.thread_work is not None:
            self.saoma = None
            self.running = False
            self.thread_work.join()
            self.thread_work = None
        self.qq.put(None)

    def close(self):
        self.stop()


def get_saoma_callback(ssw):
    def callback(ma):
    #     JOB_RECEIVE_REPORT(ssw, ma)
        return 0

    return callback


if __name__ == "__main__":
    print(text())
    # pa = pa if os.path.exists(pa) else 'E:/data/221101ptc螺钉/内二PTC螺钉-ok'
    # test_flask_client()
    # main(r'C:\Users\lenovo\Desktop\handian\Image_20211102204512630.bmp')
